$(function(){      
    $('#newGpPlaceHolder').live('click',function(){
        $(this).parent().parent().remove();
    });
    
     $('.buttonCross').live('click',function(){
         $(this).parent().remove();
     });
                                                              
}); 

  
function onGetRFID()
{
    var rfid = String(Math.random()); 
    rfid = rfid.substr(2,15);
    $('#rfid').val(rfid);
}   
/*  
function addNewDocType()
{
    var count = $('#docTypeList li').length+1;
    var button = "<div id='newDocType' class='button buttonCross' />";
    $('#docTypeList').append("<li name='new' id=" + count +" style='color:red;'>"+ $('#docTypeName').val()+"&nbsp;" + button + "</li>");
}
*/
function createNewDoc()
{
                          
    var jsonStr = '{"title":"' + $.tim( $('#title').val()) + '"';
    jsonStr = jsonStr + ',"docType":"' + ($('#dDocType').prop("selectedIndex") +1) + '"' 
    jsonStr = jsonStr + ',"docGroup":"' + ($('#dDocGroup').prop("selectedIndex") +1) + '"' 
    jsonStr = jsonStr + ',"x":"' + ($('#dRestricted').prop("checked")) + '"' 
    jsonStr = jsonStr + ',"notes":"' + $('#dNots').val() + '"' 
    jsonStr = jsonStr + ',"rfid":"' + $('#rfid').val() + '"' 
    jsonStr = jsonStr + '}';
    
}
           
function initDocGroupOptionBox(objID,docGroupList)
{
    $('#'+objID+' option').remove();
    var $dom = $('#'+objID);
      $.each(docGroupList,function(idx,value){    
          $dom.append("<option value="+value.id+" >"+value.groupName+"</option>");
          // echo "<option value=".$docGroup->id." >".$docGroup->group_name."</option>";      
      });          

}
            
function addNewDocGroup()
{
    var count = $('#docGroupTable tr').length+1;
    var button = "<div id='newGpPlaceHolder' class='button buttonCross' />";
    var groupName = $('#docGroupName').val();
    if ($.trim(groupName) == '')
        return;

    var row = "<tr name='new' style='color:red'>"
    row = row + "<td >"+ button +"</td><td>" + groupName+"</td><td>" + $('#dDepartment option:selected').text() + "<span style='visibility:hidden;'>" + ( $('#dDepartment').prop("selectedIndex") +1) + "</span>"+"</td><td>" + ( $('#dDocGroupRestricted').prop("checked") ? "yes" : "no") + "</td>";
    row = row + "</tr>";

 
    $('#docGroupTable').append(row);

  
}

function RenumberingGroup()
{
 $('#docGroupTable tr td:first-child').each(function(index){
     $(this).text(index+1);
 });
}

function saveNewDocGroup()
{
     var newGroups='[';
    
    var $newRow = $('#docGroupTable tr[name="new"]');
    var max = $newRow.length;
    var str = '';                 
    
    $newRow.each(function(idx){ 

        var tr = $(this).html();
        var td =  tr.match(/<td>.*?<\/td>/g);                           

        str = '{"groupName" : "' + td[1].match(/<td>(.*?)<\/td>/)[1]+ '",';
        
        str = str+ '"dept_id" : "' + td[2].match(/<span[^>]*>(.*?)<\/span>/)[1]+ '",';
        str= str+ '"x" : "' + ( td[3].match(/<td>(.*?)<\/td>/)[1]=='yes' ? 1 : 0) + '"}';
                                  
        //console.log('str:' + str);                
        newGroups = newGroups + str;
        if(idx <max-1)    newGroups  = newGroups  + ','
        
    });  
    newGroups = newGroups + "]"
//    newGroups = '{"newGroup":[{"groupName" : "grup2","dept" : "Administration","x" : "yes"},{"groupName" : "grup1","dept" : "Sales","x" : "yes"}]}'
    var jsobj = eval('(' + newGroups +')');
    if (newGroups.length > 0)
    {
        var url =  gbaseUrl + 'AjaxLibs/ajaxAddNewDocGroup';    
        $.post(url ,{newGroups:jsobj},
            function(data){                         
                    if(data.status =='ok')
                    {              
                        $newRow.attr('name','');
                        $newRow.css('color','black');
                        $newRow.find('#newGpPlaceHolder').remove();  
                        asynGetDocGroupList("DocGroup",initDocGroupOptionBox); //refresh docTypeOptionBox 
                        RenumberingGroup();
                    }
                    else
                       {
                           console.log('data.status.failed');
                           var errors = '';
                           $.each(data.errorlist,function(idx,value){
                                errors = errors + value.key + '->' + value.error +'<br/>';                               
                           });
                                                      
                           $('#newDocGroupDialog .wContent').append('<div id="newDocGroupError" style="color:red;">' + errors + '</div>')
                           setTimeout(function(){
                               $('#newDocGroupError').slideUp(3000);
                           },5000);

/*                           $.each(data.errorlist,function(idx,value){
                               console.log('key=>' + value.key);
                               console.log('value=>' + value.error);
                                appendErrorMessage(value.key,value.error);                               
                           });
*/                       }
              },"json");        
    }
}
                                
/*
* 
*88888888888888888888888888888888888888888888888888888888888888888888888888888888888888 
*88888888888888888888888888888888888888888888888888888888888888888888888888888888888888
* *88888888888888888888888888888888888888888888888888888888888888888888888888888888888888
* */
function asynGetdataList(id,callback, ajaxUrl)
{                                                                                                
    $.post(ajaxUrl,{},function(data){
        if (data.status=='ok')
        {              
              callback(id,data.dataList);
        }
    },"json"); 
}

                          
function onAjaxReturn_ul(id,datalist)
{
    $('#input_'+id).val('');
    $('#ul_'+id +' li').remove();
    if (id=='DocGroup')  
    {

    var $tr = $('#docGroupTable');
    var row = '';
 
      $.each(docGroupList,function(idx,value){    
          row = '<tr><td>' + (idx +1)+ '</td><td>' + value.groupName+ '</td><td>' + value.department + '</td><td>' + value.restricted + '</td></tr>';
 
          $tr.append(row);
 
      }); 
             
   }
   else
   {
        var $ul = $('#ul_'+ id);
          $.each(datalist,function(idx,value){    
               $ul.append('<li>' + value.data + '</li>');
          });             
       
   }
}

function onAjaxReturn_selOption(id,datalist)
{
    $('#'+id +' option').remove();
    var $dom = $('#'+id);
      $.each(datalist,function(idx,value){    
          $dom.append("<option value="+value.id+" >"+value.data+"</option>");
      });                                                            
}
                   
function QuickAdd_onClick(obj_id,dialogID)
{
    console.log('QuickAdd_onClick:' + obj_id +',' + dialogID);
  $('.adhocDialog').slideUp("fast");
  if (obj_id=="Department")
  {
    asynGetdataList(obj_id,onAjaxReturn_ul,gbaseUrl + 'AjaxLibs/ajaxGetDepartments');      
  }
  else if (obj_id =="DocumentType")
    asynGetdataList(obj_id,onAjaxReturn_ul,gbaseUrl + 'AjaxLibs/ajaxGetDocTypeList');
  else if (obj_id =="DocGroup")
  {
        asynGetDocGroupList(obj_id,initDocGroupList);
  }      
  
                 
    
    var pos = $('#btn_'+obj_id).position();      
                                                                                                                                                              
    // .outerWidth() takes into account border and padding.
    var width = $('#btn_'+obj_id).outerWidth();

    //show the menu directly over the placeholder
    $("#" + dialogID).css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width+10) + "px"
    }).slideDown("fast");   
}

function closeDialog()
{
    $('.adhocDialog').slideUp("fast");
}

function addNew(obj_id)
{
    console.log('addNew:'+obj_id);
    var count = $('#ul'+obj_id+' li').length+1;
    if (obj_id=="Department")
    {                                                                                      
        var button = '<div id="newDepartment" class="button buttonCross" />';
    }
    else if (obj_id =="DocumentType")
    {
        var button = '<div id="newDocType" class="button buttonCross" />';      
    }
    $('#ul_' + obj_id).append('<li name="new" id=' + count +' style="color:red;">' + $('#input_'+obj_id).val()+'&nbsp;' + button + '</li>');   
}

function onSaveChange(obj_id)
{
  if (obj_id=="Department")
  {
   saveNewDepartment(obj_id);
  }
  else if (obj_id =="DocumentType")
    _saveNewDocType(obj_id);
    
} 


function saveNewDepartment(obj_id)
{
    var newDepts=[];
    
    $('#ul_'+obj_id+' li[name="new"]').each(function(index){
        newDepts.push($.trim($(this).text()));
        console.log('found new item:' + index + '='+$(this).text() + ',name:' + $(this).attr('name'));
    });        
    if (newDepts!="")
    {
        var url =  gbaseUrl + 'AjaxLibs/ajaxAddNewDepartment';    
        $.post(url ,{newDepts:newDepts},
            function(data){                         
                    if(data.status =='ok')
                    {
                      $('#ul_'+obj_id+' li[name="new"]').each(function(index){
                        $(this).attr('name',''); //successfully added, remove 'new' flag
                        $(this).css('color','black');
                        $(this).find('.buttonCross').remove();
                      });   
                    }
                    else
                       {
                           $.each(data.errorlist,function(idx,value){
                               console.log('key=>' + value.key);
                               console.log('value=>' + value.error);
                                appendErrorMessage('#ul_'+obj_id,value.key,value.error);                               
                           });
                       }
                       asynGetdataList(onAjaxReturn_selOption,gbaseUrl + 'AjaxLibs/ajaxGetDepartments');      
  
              },"json");        
    }
}


function _saveNewDocType(obj_id)
{
    var newTypes=[];
    
    $('#ul_'+obj_id+' li[name="new"]').each(function(index){
        newTypes.push($.trim($(this).text()));
        console.log('found new item:' + index + '='+$(this).text() + ',name:' + $(this).attr('name'));
    });        
    if (newTypes!="")
    {
        var url =  gbaseUrl + 'AjaxLibs/ajaxAddNewDocTypes';    
        $.post(url ,{newTypes:newTypes},
            function(data){                         
                    if(data.status =='ok')
                    {
                      $('#ul_'+obj_id+' li[name="new"]').each(function(index){
                        $(this).attr('name',''); //successfully added, remove 'new' flag
                        $(this).css('color','black');
                        $(this).find('.buttonCross').remove();
                      });   
                    }
                    else
                       {
                           $.each(data.errorlist,function(idx,value){
                               console.log('key=>' + value.key);
                               console.log('value=>' + value.error);
                                appendErrorMessage('#ul_'+obj_id,value.key,value.error);                               
                           });
                       }
                       asynGetdataList(obj_id,onAjaxReturn_selOption,gbaseUrl + 'AjaxLibs/ajaxGetDocTypeList');      
  
              },"json");        
    }
}
function appendErrorMessage(obj_id,key, errorMsg)
{
    console.log('appendErrorMessage:' + obj_id +','+key);
    $(obj_id+' li[name="new"]').each(function(index){
        console.log(key + (key == $.trim($(this).text()) ? '==' : '!=') + $.trim($(this).text()));
        $(this).attr('name',''); //successfully added, remove 'new' flag
        if (key == $.trim($(this).text()))
        {
            $(this).text($(this).text() + '(' + errorMsg +')');
            console.log('errorMsg:' +errorMsg);                                    
            return false;                      
        }
        else
        {
            $(this).css('color','black');
            $(this).find('.buttonCross').remove();            
        }
        
    });            
}   

function asynGetDocGroupList(obj_id,callback)
{
     var url =  gbaseUrl + 'AjaxLibs/ajaxGetDocGroupList';
    $.post(url,{},function(data){
        if (data.status=='ok')
        {          
              callback(obj_id,data.dataList);
        }
    },"json");     
}

function initDocGroupList(obj_id,docGroupList)
{
    console.log('initDocGroupList:' + docGroupList);
  $('#docGroupName').val('');
    $('#docGroupTable tr').remove();
    var $tr = $('#docGroupTable');
    var row = '';
 
      $.each(docGroupList,function(idx,value){                   
          row = '<tr><td>' + (idx +1)+ '</td><td>' + value.groupName+ '</td><td>' + value.department + '</td><td>' + ((value.restricted=='1')? 'yes' :'no') + '</td></tr>';
 
          $tr.append(row);
 
      });          
                        
}               